<template>
  <div style="display: flex" class="menmuStyle tempxyz">
    <CCard class="leftCard" style>
      <div class="manageBtn" style>
        <!-- <CButton
            v-c-tooltip="'添加节点'"
            title="添加节点"
            variant="outline"
            color="rgb(2,40,88)"
            @click="addTreeNode"
            data-permission="Btn_Dict_AddR"
          >
            <img class="featuresstyle" src="@/assets/icons/增加同级.svg" alt />
          </CButton>
          <CButton
            v-c-tooltip="'删除树节点'"
            title="删除树节点"
            variant="outline"
            color="rgb(2,40,88)"
            @click="delTreeNode"
            style="margin-left: 6px"
            data-permission="Btn_Dict_DelR"
          >
            <img class="featuresstyle" src="@/assets/icons/delete.svg" alt />
          </CButton> -->

        <!-- <CButton
          title="添加同级"
          variant="outline"
          class="headTextBtnStyle system-btn-style"
          @click="addSameTreeNode"
          data-permission="Btn_Dict_AddR"
        >
          添加同级
        </CButton> -->
        <CButton
          title="添加节点"
          variant="outline"
          class="headTextBtnStyle system-btn-style"
          @click="addTreeNode"
          data-permission="Btn_Dict_AddR"
        >
          添加节点
        </CButton>
        <CButton
          title="删除节点"
          variant="outline"
          class="headTextBtnStyle system-btn-style"
          @click="delTreeNode"
          style="margin-left: 6px"
          data-permission="Btn_Dict_DelR"
        >
          删除节点
        </CButton>
      </div>
      <div class="taskType-treeDiv">
        <ul id="dictTree" class="ztree customStyleZtree"></ul>
      </div>
    </CCard>
    <CCard class="rightCard">
      <CCardHeader class="header-wraper">
        <div class="header-left-titleWraper">
          <span class="textTitle">{{ dictName }}列表</span>
        </div>
        <div class="header-right-wraper">
          <CButton
            color="info"
            @click="addCatalog"
            class="system-btn-style"
            data-permission="Btn_Dict_Add"
          >
            <CIcon name="cil-plus" />&nbsp;字典项
          </CButton>
        </div>
      </CCardHeader>
      <CCardBody class="card-body">
        <div style="height: calc(100% - 46px)">
          <TableList ref="table" :getColumn="getColumns" :getAxios="getAxios">
            <template v-slot:show_details="item">
              <CButton
                title="查看"
                variant="outline"
                class="textBtnStyle onButton system-btn-style"
                @click="getInfo(item.data.row)"
                >查看</CButton
              >
              <CButton
                title="编辑"
                variant="outline"
                class="textBtnStyle onButton system-btn-style"
                @click="update(item.data.row)"
                data-permission="Btn_Dict_Up"
                >编辑</CButton
              >
              <CButton
                title="删除"
                variant="outline"
                class="textBtnStyle onButton system-btn-style"
                @click="del(item.data.row.id)"
                data-permission="Btn_Dict_Del"
                >删除</CButton
              >
            </template>
          </TableList>
        </div>
      </CCardBody>
      <!--    <div class="dictManage borderStyle">
           <CDataTable :items="data" :fields="fields" hover border>
             <template #show_details="{ item }">
               <td class="py-2" align="center">
                 &lt;!&ndash; <CButton
                   v-c-tooltip="'查看'"
                   title="查看"
                   variant="outline"
                   style="margin-right: 5px"
                   @click="getInfo(item)"
                 >
                   <CIcon
                     class="featuresstyle colortempstyle"
                     name="cil-line-spacing"
                   />
                 </CButton>
                 <CButton
                   v-c-tooltip="'编辑'"
                   title="编辑"
                   color="rgb(2,40,88)"
                   variant="outline"
                   style="margin-right: 5px"
                   @click="update(item)"
                   data-permission="Btn_Dict_Up"
                 >
                   <img
                     class="featuresstyle"
                     src="@/assets/icons/edit.svg"
                     alt
                   />
                 </CButton>
                 <CButton
                   v-c-tooltip="'删除'"
                   title="删除"
                   color="rgb(2,40,88)"
                   variant="outline"
                   style="margin-right: 5px"
                   @click="del(item.id)"
                   data-permission="Btn_Dict_Del"
                 >
                   <img
                     class="featuresstyle"
                     src="@/assets/icons/delete.svg"
                     alt
                   />
                 </CButton> &ndash;&gt;
                 <CButton
                   title="查看"
                   variant="outline"
                   class="textBtnStyle"
                   @click="getInfo(item)"
                 >
                 查看
                 </CButton>
                 <CButton
                   title="编辑"
                   variant="outline"
                   class="textBtnStyle"
                   @click="update(item)"
                   data-permission="Btn_Dict_Up"
                 >
                 编辑
                 </CButton>
                 <CButton
                   title="删除"
                   variant="outline"
                   class="textBtnStyle"
                   @click="del(item.id)"
                   data-permission="Btn_Dict_Del"
                 >
                 删除
                 </CButton>
               </td>
             </template>
           </CDataTable>
         </div>
       </CCardBody>
       <CCardFooter class="pageLink">
         <CRow>
           <CCol class="footerPage" style>
             <span class="pageContent">
               每页
               <CSelect
                 @change="getVendorId($event)"
                 :options="[10, 15, 20, 25]"
                 v-model="pageSize"
                 class="selectStyle"
                 style
               />
               条记录。第{{ this.currentPage }}页(总共{{ this.total }}页，{{
                 this.allNum
               }}条记录)
             </span>
             <CPagination
               :activePage.sync="currentPage"
               :pages="total"
               align="end"
               v-if="total != 0"
             />
           </CCol>
         </CRow>
       </CCardFooter>-->
    </CCard>
    <Modal
      v-model="delShow"
      draggable
      scrollable
      title="删除字典项"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">删除字典项</span>
      </p>
      <div class="modalBody">
        <p>删除字典项时与字典项相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="delNodeShow"
      draggable
      scrollable
      title="删除节点字典项"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">删除节点字典项</span>
      </p>
      <div class="modalBody">
        <p>删除节点字典项时与字典项相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delNodeCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delNodeOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="addShow"
      draggable
      scrollable
      title="新建字典项"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">新建字典项</p>
      <CRow>
        <CCol md="12">
          <CForm>
            <CInput
              label="字典项编码"
              placeholder="请输入字典项编码"
              horizontal
              v-model="addData.dictCode"
            />
            <CInput
              label="字典项名称"
              placeholder="请输入字典项名称"
              horizontal
              v-model="addData.dictName"
            />
            <CInput
              label="备注"
              placeholder="请输入备注"
              horizontal
              v-model="addData.memo"
            />
          </CForm>
        </CCol>
      </CRow>
      <template #footer class="footerBtns">
        <CButton @click="addCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="addOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="updateShow"
      draggable
      scrollable
      title="更新字典项"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">更新字典项</p>
      <CRow>
        <CCol md="12">
          <CForm>
            <CInput
              label="字典项编码"
              placeholder="请输入字典项编码"
              horizontal
              v-model="upData.dictCode"
              readonly
            />
            <CInput
              label="字典项名称"
              placeholder="请输入字典项名称"
              horizontal
              v-model="upData.dictName"
            />
            <CInput
              label="备注"
              placeholder="请输入备注"
              horizontal
              v-model="upData.memo"
            />
          </CForm>
        </CCol>
      </CRow>
      <template #footer class="footerBtns">
        <CButton @click="updateCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="updateOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="getShow"
      draggable
      scrollable
      title="查看字典项"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">查看字典项</p>
      <CRow>
        <CCol md="12">
          <CForm>
            <CInput
              label="字典项编码"
              horizontal
              v-model="catalogData.dictCode"
              readonly
            />
            <CInput
              label="字典项名称"
              horizontal
              v-model="catalogData.dictName"
              readonly
            />
            <CInput
              label="备注"
              horizontal
              v-model="catalogData.memo"
              readonly
            />
            <CInput
              label="版本号"
              horizontal
              v-model="catalogData.version"
              readonly
            />
            <CInput
              label="创建时间"
              horizontal
              v-model="catalogData.createTime"
              readonly
            />
            <CInput
              label="更新时间"
              horizontal
              v-model="catalogData.updateTime"
              readonly
            />
            <CInput
              label="优先级"
              horizontal
              v-model="catalogData.sortOrder"
              readonly
            />
          </CForm>
        </CCol>
      </CRow>
      <template #footer class="footerBtns">
        <CButton @click="getCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="getOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
  </div>
</template>

<script>
const fields = [
  {
    label: "序号",
    key: "number",
    _style: "width:80px;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "字典项名称",
    key: "dictName",
    _style: "width:auto;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "字典项编码",
    key: "dictCode",
    _style: "width:auto;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "备注",
    key: "memo",
    _style: "width:auto;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "创建时间",
    key: "createTime",
    _style: "width:170px;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    key: "show_details",
    label: "操作",
    _style: "width:240px;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
];
import endIcon from "@/assets/icons/endIcon.png";
import failedIcon from "@/assets/icons/failedIcon.png";
import TableList from "@/template/table/TableList";

export default {
  name: "dictManage",
  components: { TableList },
  data() {
    return {
      modalStyle: { top: "250px" },
      selectactionid: 0,
      delShow: false,
      delNodeShow: false,
      getShow: false,
      updateShow: false,
      addShow: false,
      isSameLevel: false,
      loading: true,
      data: [],
      fields,
      clickId: -1,
      currentPage: 1,
      pages: 0,
      total: 0,
      allNum: 0,
      select: "processmodel",
      pageSize: 15,
      treeData: [],
      selectTreeId: "0",
      dictName: "",
      addData: {
        dictCode: "",
        dictName: "",
        memo: "",
        parentId: "",
      },
      catalogData: {
        id: "",
        createTime: "",
        updateTime: "",
        version: -1,
        createBy: "",
        dictCode: "",
        dictName: "",
        isTree: -1,
        memo: "",
        parentId: "0",
        sortOrder: "",
        updateBy: "",
      },
      upData: {
        dictCode: "",
        dictName: "",
        memo: "",
        parentId: "",
      },

      getColumns: [
        {
          title: "字典项名称",
          key: "dictName",
        },
        {
          title: "字典项编码",
          key: "dictCode",
        },
        {
          title: "备注",
          key: "memo",
        },
        {
          title: "创建时间",
          key: "createTime",
          className: "centerText",
          width: 170,
        },
        {
          title: "操作",
          key: "show_details",
          slot: "show_details",
          className: "centerText",
          width: 220,
        },
      ],
      getAxios: {
        url: this.$api.manageApi.getDictByParentId, //请求路径
        method: "get", //请求方式
        dataList: { parentId: 1 }, //请求参数
      },
    };
  },
  computed: {
    getColumn() {
      return [
        { key: "number", title: "序号", align: "center" },
        { key: "dictName", title: "字典项名称", align: "center" },
        { key: "dictCode", title: "字典项编码", align: "center" },
        { key: "memo", title: "备注", align: "center" },
        { key: "createTime", title: "创建时间", width: 200, align: "center" },
        {
          title: "操作",
          width: "200px",
          slot: "action",
          align: "center",
        },
      ];
    },
  },
  mounted() {
    this.getDictCodeTree();
    // this.getDictByParentId(2);
  },
  methods: {
    /**
     * 分页功能实现
     */
    getDictByParentId(parentId) {
      let self = this;
      // self.selectactionid = parentId;
      self.data = [];
      let path = self.$api.manageApi.getDictByParentId;
      let param = {
        parentId: parentId,
        pageSize: this.pageSize,
        pageNum: self.currentPage,
      };
      let getAxiosData = {
        url: path,
      };
      self.$refs.table.getRefreshTable(param, getAxiosData);
      /*    self.http.get(path, param).then((res) => {
        if (res.data.success == true) {
          self.data = res.data.data.dictCodeList;
          self.allNum = res.data.data.total;
          self.total = Math.ceil(res.data.data.total / self.pageSize);
          for (let i = 0; i < self.data.length; i++) {
            self.data[i].number =
                    (self.currentPage - 1) * self.pageSize + i + 1;
          }
        } else {
          self.$Message.error(res.data.message);
        }
      });*/
    },

    /**
     * 获取每页对应的value值，并转为数值型
     */
    getVendorId(event) {
      let tempdata = event.target.value;
      this.pageSize = parseInt(tempdata);
    },
    /**
     * 点击查看按钮，显示弹窗，获取id和val值
     */
    getInfo(val) {
      this.getShow = true;
      this.clickId = val.id;
      this.catalogData = val;
    },
    /**
     * 点击取消按钮，关闭弹窗
     */
    getCancel() {
      this.getShow = false;
    },
    /**
     * 点击确定按钮，关闭弹窗
     */
    getOk() {
      this.getShow = false;
    },
    /**
     * 点击编辑按钮，显示弹窗，获取id和val值
     */
    update(val) {
      this.updateShow = true;
      this.clickId = val.id;
      this.upData = JSON.parse(JSON.stringify(val)); //deep copy
    },
    /**
     * 点击删除按钮，显示弹窗，获取id值
     */
    del(id) {
      this.delShow = true;
      this.clickId = id;
    },
    /**
     * 点击删除树节点按钮，显示弹窗，获取此id值
     */
    delTreeNode() {
      this.delNodeShow = true;
    },
    /**
     * 点击增加字典项按钮，显示弹窗
     */
    addCatalog() {
      this.addShow = true;
    },
    //表格删除确定
    delOk() {
      let self = this;
      this.delShow = false;
      if (!self.clickId) {
        this.$Message.warning("请先选择要删除的数据");
        return;
      }
      if (self.clickId == "1") {
        this.$Message.warning("不能删除根节点");
        return;
      }

      let path = this.$api.manageApi.deleteById + "/" + self.clickId;
      this.http.get(path).then((res) => {
        if (res.data.success) {
          this.$Message.success(res.data.message);
          self.getDictCodeTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    delCancel() {
      this.delShow = false;
    },
    delNodeCancel() {
      this.delNodeShow = false;
    },
    //节点删除确定
    delNodeOk() {
      let _this = this;
      this.delNodeShow = false;

      if (_this.selectTreeId === "1") {
        this.$Message.warning("不能删除根节点");
        return;
      }

      let path = this.$api.manageApi.deleteById + "/" + _this.selectTreeId;
      this.http.get(path).then((res) => {
        if (res.data.success) {
          this.$Message.success(res.data.message);

          //删除子节点时 设置父节点选中；一级节点删除后 选中的节点设置为根节点selectTreeId='1'；
          let treeObj = $.fn.zTree.getZTreeObj("dictTree");
          let node = treeObj.getNodeByParam("id", _this.selectTreeId);
          if (node.pId) _this.selectTreeId = node.pId;
          else this.selectTreeId = "1";

          _this.getDictCodeTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    addSameTreeNode() {
      this.isSameLevel = true;
      this.addShow = true;
    },
    addTreeNode() {
      this.isSameLevel = false;
      this.addShow = true;
    },
    addOk() {
      let self = this;
      let path = this.$api.manageApi.apiCreate;
      if (!self.selectTreeId) {
        this.$Message.warning("请选择节点");
        return;
      }

      if (this.isSameLevel) {
        //同级
        let treeObj = $.fn.zTree.getZTreeObj("dictTree");
        if (!treeObj && treeObj.getSelectedNodes().length < 1) return;

        let parentId = treeObj.getSelectedNodes()[0].pId;
        self.addData.parentId = parentId ? parentId : "0";
      } else {
        //子级
        self.addData.parentId = self.selectTreeId;
      }

      this.http.post(path, self.addData).then((res) => {
        if (res.data.success) {
          this.$Message.success(res.data.message);
          self.getDictCodeTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
      this.addShow = false;
      self.addData = {
        dictCode: "",
        dictName: "",
        memo: "",
        parentId: "",
      };
    },
    addCancel() {
      this.addShow = false;
    },
    updateOk() {
      let self = this;
      let path = this.$api.manageApi.updateDictCodeById + "/" + self.clickId;
      let param = self.upData;
      this.http.post(path, param).then((res) => {
        this.updateShow = false;
        if (res.data.success) {
          this.$Message.success(res.data.message);

          self.getDictCodeTree();
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    updateCancel() {
      this.updateShow = false;
    },
    getDictCodeTree() {
      let self = this;
      self.treeData = [];
      let path = this.$api.manageApi.getDictCodeTree;
      this.http.get(path).then((res) => {
        self.loading = false;
        if (res.data.success) {
          self.treeData = res.data.data;
          // 实现的效果非常奇怪，当删除只有一条数据时 刷新左侧树
          if (self.treeData.length < 1) {
            $.fn.zTree.init($("#dictTree"), setting, []);
            return;
          }
          if (self.selectTreeId === "0") {
            //修改初始化设置id为树节点索引为0的id(因为当前树节点没有id为0的数据)
            self.selectTreeId = self.treeData[0].id;
          }
          if (self.selectTreeId) {
            self.setTreeNodeStatus(self.treeData);
            self.getDictByParentId(self.selectTreeId);
          }

          let setting = {
            data: {
              simpleData: {
                enable: true,
              },
            },
            view: {
              showLine: false,
              showIcon: false,
            },
            callback: {
              onClick: this.zTreeOnClick,
            },
          };

          let treeObj = $.fn.zTree.init($("#dictTree"), setting, self.treeData);

          //设置节点选中状态
          let node = treeObj.getNodeByParam("id", self.selectTreeId, null);
          treeObj.selectNode(node);
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    //选中节点设置展开
    setTreeNodeStatus(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === this.selectTreeId) {
          data[i].open = true;
          break;
        }
        let children = data[i].children;
        if (children && children.length > 0) {
          this.setTreeNodeStatus(children);
        }
      }
    },
    zTreeOnClick(event, treeId, treeNode) {
      let self = this;

      self.selectTreeId = treeNode.id;
      self.dictName = treeNode.name;
      this.getDictByParentId(self.selectTreeId);
    },
  },
  watch: {
    data(newVal, oldVal) {
      this.$nextTick(function () {
        this.GlobalPermissionRender.render();
      });
    },
    pageSize(newVal, oldVal) {
      this.pageSize = newVal;
      this.getDictByParentId(this.selectactionid);
    },
    currentPage(newVal, oldVal) {
      this.currentPage = newVal;
      this.getDictByParentId(this.selectactionid);
    },
  },
};
</script>
<style scoped>
.col-md-2 {
  padding-right: 10px;
  padding-left: 20px;
}
.col-md-10 {
  padding-right: 20px;
  padding-left: 0px;
}
.manageBtn {
  border-bottom: 1px solid #d8d8d8;
  margin-top: 15px;
  padding-bottom: 15px;
  display: flex;
  justify-content: space-evenly;
}

::-webkit-scrollbar-thumb {
  background-color: #7eb8ee;
}
.dic_tree {
  max-width: 230px;
  overflow-y: auto;
  height: 100%;
}

/* 分页 */
.footerPage {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
  color: black;
}
.pageContent {
  margin-right: 26px;
  font-size: 14px;
}
.selectStyle {
  display: inline-block;
  width: 100px;
  margin-right: 5px;
}

.treeDiv {
  overflow-x: hidden;
  overflow-y: auto;
}
.userTitle {
  margin-bottom: 0 !important;
  margin-top: 5px;
}
.card {
  margin-top: 0;
}

.dictManage {
  height: 100%;
  overflow-y: auto;
}
</style>

<style scoped>
.taskType-treeDiv {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 10px;
}
.menmuStyle {
  height: 100%;
}
.imageControl-treeDiv {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 10px;
}
.ztree {
  margin: 0;
  padding: 0;
}
.rightCard {
  width: 80%;
  margin-left: 10px;
  flex: 1;
}

.leftCard {
  width: 18%;
}
/deep/.card {
  margin-bottom: 0;
}
/deep/.ivu-table td.centerText {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  text-align: -moz-center;
  text-align: -webkit-center;
}
.onButton:hover {
  color: white;
}
/deep/ footer.page-link:hover {
  background-color: #ffffff;
}

.tempxyz .card-body {
  height: calc(100% - 70px) !important;
}
</style>
